package cn.spring.rabbitmq.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 *
 * @Author tanyong
 * @Version RabbitmqTemplatePostProcessor v1.0.0 2025/9/16 17:44 $$
 */
@Slf4j
public class RabbitmqTemplatePostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof RabbitTemplate) {
            RabbitTemplate rabbitTemplate = (RabbitTemplate) bean;

            // 启用发送确认机制（ConfirmCallback）
            rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
                @Override
                public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                    if (ack) {
                        log.info("消息成功发送到交换机，correlationData: {}", correlationData);
                    } else {
                        log.error("消息发送到交换机失败，correlationData: {}, cause: {}", correlationData, cause);
                    }
                }
            });

            // 启用发送失败回调机制（ReturnCallback）
            rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
                @Override
                public void returnedMessage(ReturnedMessage returnedMessage) {
                    log.error("消息无法路由到队列，exchange: {}, routingKey: {}, message: {}, replyCode: {}, replyText: {}",
                            returnedMessage.getExchange(),
                            returnedMessage.getRoutingKey(),
                            returnedMessage.getMessage(),
                            returnedMessage.getReplyCode(),
                            returnedMessage.getReplyText());
                }
            });

            // 设置消息持久化
            rabbitTemplate.setMandatory(true);

            log.info("RabbitTemplate 配置完成：启用 ConfirmCallback、ReturnsCallback 和消息持久化");
        }
        return bean;
    }

}
